package cashhandler

import (
	"github.com/gin-gonic/gin"
	"github.com/shopspring/decimal"
	"yundian/internel/app/dao"
	"yundian/internel/app/helper"
	"yundian/internel/app/helper/request"
	"yundian/internel/app/models/cashlog"
	"yundian/internel/pkg/dingo"
	. "yundian/internel/pkg/dingo/result"
)

func GetCashWithDrawalList(ctx *gin.Context) {
	param := &request.CashListReq{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()

	userId, err := helper.GetUserIdFromCtx(ctx)
	IsAdmin, err := helper.GetIsAdminFromCtx(ctx)
	parentId, err := helper.GetParentIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()

	if IsAdmin == helper.TypeNumIsAdminAdministrator || (IsAdmin == helper.TypeNumIsAdminStaff && parentId == 2) {
		param.UserId = 2
	} else {
		param.UserId = userId
	}

	data := dao.NewCashDao().GetCashList(param)
	lists := data.Unwrap().([]*cashlog.UserWithdrawalLog)

	for _, lst := range lists {
		divindsMoney := dao.NewOrderDao().GetDividendsMoneyByUserId(lst.UserID).Unwrap().(int64) // 计算分红收益
		cashMoney := dao.NewOrderDao().GetCashLogByUserId(lst.UserID).Unwrap().(int64)           // 已提现金额

		balance := decimal.NewFromInt(divindsMoney).Sub(decimal.NewFromInt(cashMoney))
		lst.Balance = balance.Div(decimal.NewFromInt(100)).StringFixed(2) // 可提现金额
		lst.DivindsMoney = decimal.NewFromInt(divindsMoney).Div(decimal.NewFromInt(100)).StringFixed(2) // 累计收益
		lst.CashMoney = decimal.NewFromInt(cashMoney).Div(decimal.NewFromInt(100)).StringFixed(2) // 已提现金额
	}

	Response(ctx)("", CodeSuccess, ResponseList{
		PageNo:     param.PageNo,
		PageSize:   param.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  (data.Val().(int64) + int64(param.PageSize) - 1) / int64(param.PageSize),
		Data:       lists,
	})(OK)
}
